package com.minivision.fdiot.mqtt;

import java.io.IOException;
import java.sql.Time;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.minivision.fdiot.mqtt.auth.FaceDeviceAuthenticator;

import io.moquette.BrokerConstants;
import io.moquette.server.Server;
import io.moquette.server.config.MemoryConfig;
import lombok.extern.slf4j.Slf4j;

/**
 * MQTT启动器
 * @author hughzhao
 * @2018年3月2日
 */
@Component
@Slf4j
public class MqttStartup {

	/**
	 * deviceAuthenticator
	 */
	@Autowired
	private FaceDeviceAuthenticator deviceAuthenticator;

	/**
	 * mqttBroker
	 */
	@Autowired
	private Server mqttBroker;

	/**
	 * handler
	 */
	@Autowired
	private ServerInterceptHandler handler;

	/**
	 * port
	 */
	@Value("${mqtt.server.port:1883}")
	private int port = 1883;

	/**
	 * delay
	 */
	@Value("${mqtt.delay:15000}")
	private long delay = 15000l;
	
	/**
	 * Description: <br>
	 * 
	 * @author guming <br>
	 * @taskId 
	 * @param 
	 * @return <br>
	 */
	@PostConstruct
	public void start() throws Exception {
		Timer timer = new Timer();
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				try {
					startBroker();
				}catch (Exception e){

				}
			}
		},delay);

	}
	
	/**
	 * Description: <br>
	 * 
	 * @author guming <br>
	 * @taskId 
	 * @param 
	 * @return <br>
	 */
	@PreDestroy
	public void stop() throws Exception {
	  mqttBroker.stopServer();
      log.info("MQTT Broker stopped");
	}

	/**
	 * Description: <br>
	 * 
	 * @author guming <br>
	 * @taskId 
	 * @param 
	 * @return <br>
	 */
	private void startBroker() throws IOException {
		Properties props = new Properties();
		props.put(BrokerConstants.PORT_PROPERTY_NAME, "" + port);
		props.put(BrokerConstants.HOST_PROPERTY_NAME, BrokerConstants.HOST);
		props.put(BrokerConstants.WEB_SOCKET_PORT_PROPERTY_NAME, BrokerConstants.DISABLED_PORT_BIND);
		props.put(BrokerConstants.ALLOW_ANONYMOUS_PROPERTY_NAME, Boolean.FALSE.toString());
		//props.put(BrokerConstants.INTERCEPT_HANDLER_PROPERTY_NAME,"io.moquette.interception.HazelcastInterceptHandler");
		mqttBroker.startServer(new MemoryConfig(props), null, null, deviceAuthenticator, null);
		mqttBroker.addInterceptHandler(handler);
		// Bind a shutdown hook
		/*Runtime.getRuntime().addShutdownHook(new Thread() {
			@Override
			public void run() {
				mqttBroker.stopServer();
				logger.info("MQTT Broker stoped");
			}
		});*/
		log.info("MQTT Broker started on port: " + port + " (tcp)");
	}
	
}
